from django.core.cache import cache

from .login_dec import get_user_by_request


def topic_cache(expire):
    def _topic_cache(func):
        def wrapper(request, *args, **kwargs):
            # 判断是否是文章详情页,是,不做缓存
            if 't_id' in request.GET.keys():
                return func(request, *args, **kwargs)
            # 以下是文章列表页,需要缓存
            # 访问者
            visitor = get_user_by_request(request)
            # 作者,(博主)
            author_id = kwargs['author_id']
            print(visitor, author_id)
            if visitor == author_id:
                # 博主自己
                cache_key = 'topic_cache_self_%s' % (request.get_full_path())
            else:
                # 非博主访问
                cache_key = 'topic_cache_%s' % (request.get_full_path())
            print('---cache key is %s-' % cache_key)
            # 缓存中心思想
            res = cache.get(cache_key)
            # 缓存有数据
            if res:
                print('----redis cache in-----')
                return res
            # 缓存中没有数据
            # 调用装饰器修饰的视图方法(get)
            res = func(request,*args,**kwargs)
            # 将结果保存到缓存
            cache.set(cache_key,res,expire)
            # 返回结果
            return res




        return wrapper

    return _topic_cache
